package com.app.aipass.activity.order;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.aipass.BR;
import com.app.aipass.R;
import com.app.aipass.app.AppViewModelFactory;
import com.app.aipass.databinding.FragmentOrderRecordTabBinding;
import com.app.aipass.entity.Message;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;

/**
 * @author: woking
 * @date: 2021/6/7
 * @description：
 * 订单记录
 */
public class OrderRecordTabFragment extends BaseFragment<FragmentOrderRecordTabBinding, OrderRecordTabViewModel> {

    private int type = 0;
    private boolean isOrder = true;
    private Disposable mSubscription;

    public static OrderRecordTabFragment newInstance(int invitationType, boolean isOrder) {
        OrderRecordTabFragment fragment = new OrderRecordTabFragment();
        Bundle args = new Bundle();
        args.putInt("Type", invitationType);
        args.putBoolean("isOrder",isOrder);//isOrder true订单  false挂单
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initParam() {
        super.initParam();
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_order_record_tab;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public OrderRecordTabViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(OrderRecordTabViewModel.class);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mSubscription != null) {
            RxSubscriptions.remove(mSubscription);
        }
    }

    @Override
    public void initData() {
        if (getArguments() != null) {
            type = getArguments().getInt("Type");
            viewModel.type.setValue(type);
            isOrder = getArguments().getBoolean("isOrder",true);
            viewModel.isOrder.setValue(isOrder);
        }

        mSubscription = RxBus.getDefault().toObservable(Message.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(new Consumer<Message>() {
                    @Override
                    public void accept(final Message message) throws Exception {
                        Log.e("TAG",type + "===============message=============="+message.getName());

                        boolean isUpload = false;
                        if(viewModel.isOrder.getValue() && message.getName().equals("sell_order"))
                        {
                            isUpload = true;
                        }
                        else if(!viewModel.isOrder.getValue() && message.getName().equals("buy_order"))
                        {
                            isUpload = true;
                        }

                        if(message.getName().equals("buy_order"))
                        {
                            viewModel.isOrder.setValue(true);
                        }
                        else if(message.getName().equals("sell_order"))
                        {
                            viewModel.isOrder.setValue(false);
                        }
//                        showDialog("");
//                        //请求网络数据
//                        viewModel.requestNetWork(false);

                        isFirstLoad = true;
//                        Log.e("TAG",isUpload + "=====isUpload==========message====HTTP======type===="+type + "  message.getType():" + message.getData());
                        if (isUpload && type == message.getType())
                        {
                            showDialog("");
                            //请求网络数据
//                            viewModel.requestNetWork(false);
                            binding.twinklingRefreshLayout.autoRefresh();
                            isFirstLoad = false;
                        }
                    }
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);

        binding.myrecyclerview.setEmptyView(binding.emptyView);
        //给RecyclerView添加Adpter，请使用自定义的Adapter继承BindingRecyclerViewAdapter，重写onBindBinding方法，里面有你要的Item对应的binding对象。
        // Adapter属于View层的东西, 不建议定义到ViewModel中绑定，以免内存泄漏
//        binding.setAdapter(new BindingRecyclerViewAdapter());
//        showDialog("");
//        //请求网络数据
//        viewModel.requestNetWork(false);

        initRefreshLayout();
    }
    public boolean isFirstLoad = true;
    @Override
    public void onResume() {
        super.onResume();
//        Log.e("TAG","============onResume======HTTP======");
        if (isFirstLoad)
        {
            // 将数据加载逻辑放到onResume()方法中
            showDialog("");
            //请求网络数据
//            viewModel.requestNetWork(false);
            binding.twinklingRefreshLayout.autoRefresh();
            isFirstLoad = false;
        }
    }
    private void initRefreshLayout()
    {
        binding.twinklingRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.onRefresh();
            }
        });
        binding.twinklingRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.onLoadMore();
            }
        });
//        binding.twinklingRefreshLayout.autoRefresh();
    }

    //    private void initRefreshLayout()
//    {
//        MySinaRefreshView headerView = new MySinaRefreshView(getActivity());
//        headerView.setTextColor(0xff745D5C);
//        binding.twinklingRefreshLayout.setHeaderView(headerView);
////        SwipeRefreshLayout
//
//        //是否需要下拉刷新,默认需要true
//        binding.twinklingRefreshLayout.setEnableRefresh(true);
//
//        //是否需要加载更多,默认需要true
//        binding.twinklingRefreshLayout.setEnableLoadmore(true);
//
//        //是否自动加载更多, 滑到底部默认加载更多,默认false
//        binding.twinklingRefreshLayout.setAutoLoadMore(true);
//
//        //如果你想进入到界面的时候主动调用下刷新，可以调用startRefresh()/startLoadmore()方法。
////        binding.twinklingRefreshLayout.startRefresh();
//        // mBinding.refreshLayout.startLoadMore();
//
//        //是否允许进入越界回弹模式,默认true
//        binding.twinklingRefreshLayout.setEnableOverScroll(true);
//
//        //是否开启悬浮刷新模式(支持切换到像SwipeRefreshLayout一样的悬浮刷新模式),默认false
//        binding.twinklingRefreshLayout.setFloatRefresh(true);
//
//        //TwinklingRefreshLayout不会自动结束刷新或者加载更多，需要手动控制
//        binding.twinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
//            @Override
//            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
//                super.onRefresh(refreshLayout);
//                viewModel.onRefresh();
////                new Handler().postDelayed(() -> {
////                    refreshLayout.finishRefreshing();
////                    viewModel.dismissDialog();
////                }, 1000);
//            }
//
//            @Override
//            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
//                super.onLoadMore(refreshLayout);
//                viewModel.onLoadMore();
////                new Handler().postDelayed(() -> {
////                    refreshLayout.finishLoadmore();
////                    viewModel.dismissDialog();
////                }, 1000);
//            }
//        });
//    }
    @Override
    public void initViewObservable() {
        //监听下拉刷新完成
        viewModel.uc.finishRefreshing.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishRefresh();
                dismissDialog();
            }
        });
        //监听上拉加载完成
        viewModel.uc.finishLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishLoadMore();
//                viewModel.dismissDialog();
            }
        });
    }
}